<template>
	<view>
		<view class="page">
			<textarea placeholder-class="phcolor" placeholder="请输入遇到的问题或建议..." class="feedback" maxlength="200"
				@input="onTextarea" :enableNative="false" :value="content" />
			<view class="uploadImg">
				<block v-for="(item,index) in images" :key="index">
					<view class="uploadFile">
						<image mode="scaleToFill" :src="item" :data-index="index" @tap="viewImgs" :lazy-load="false" />
						<view class="removeImg" @tap="removeImg" :data-index="index"
							:style="'background-image:url('+imgUrl+ '/shopImg/assets/images/profile/feedback/x2.png);'">
						</view>
					</view>
				</block>
				<view @tap="uploadFile" class="uploadFile">
					<image mode="scaleToFill" :src="imgUrl+ '/shopImg/assets/images/uploadFile.png'"
						:lazy-load="false" />
				</view>
			</view>
			<view class="form-row">
				<view class="form-row-label">联系电话</view>
				<view class="form-row-content">
					<input placeholder-class="phcolor" class="input" type="number" maxlength="11" placeholder="请输入本人手机号"
						@input="onInput" :value="phone" />
				</view>
			</view>
			<view class="btnBox">
				<!-- <button disabled="{{(content && phone) ? false : true}}" size="default" type="primary" class="btn" onTap="save">提交</button> -->
				<button size="default" :disabled="isDisabled" type="primary" class="btn" @tap="save">提交</button>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		imageDelete
	} from '@/service/uploadFile'

	import {
		addFeedback
	} from '@/service/profile.js'

	import {
		baseURL,
		imgUrl
	} from '@/service/config.js'

	export default {
		data() {
			return {
				images: [],
				content: "",
				phone: "",
				files: [],
				isDisabled: false,
				imgUrl: imgUrl
			}
		},
		methods: {
			/**
			 * 输入反馈内容触发事件
			 * @method onTextarea
			 * @param {*} e
			 */
			onTextarea(e) {
				const {value} = e.detail;
				this.content= value;
			},
			/**
			 * 输入联系电话触发事件
			 * @method onInput
			 * @param {*} e
			 */
			onInput(e) {
				const { value } = e.detail;
				this.phone = value;
			},
			/**
			 * 点击上传图片触发事件
			 * @method uploadFile
			 */
			uploadFile() {
				const _this = this;
				if (this.images.length < 3) {
					uni.chooseImage({
						count: 3,
						success: res => {
							const path = res.tempFilePaths;
							const images = this.images.concat(res.tempFilePaths)
							this.images = images;
							let userInfoData = uni.getStorageSync('userInfo');
							let header = {
								'Authorization': userInfoData.token
							};

							for (let i = 0; i < path.length; i++) {
								uni.uploadFile({
									url: '' + baseURL + '/file/imageUploads',
									fileType: 'image',
									name: 'file',
									filePath: path[i],
									header: header,
									formData: {
										// 'userId': _this.data.userId
										/**
										 * 图片上传根据手机号分类
										 * 2020.06.15
										 * Lichunchao
										 */
										"userId": _this.mobile
									},
									success: res => {
										// my.alert({ title: '上传成功' });
										const resultData = JSON.parse(res.data);
										// const file = resultData.files.file;
										const newfiles = this.files;
										// files.push(resultData.data.url)
										newfiles.push(resultData.data.url)
										// const inputName = e.currentTarget.dataset.name;
										// const inputVal = e.detail.value;
										// this.setData({
										//   [inputName]: inputVal
										// })

										this.files = newfiles
									},
									fail: function(res) {
										uni.showToast({
											title: '上传失败'
										})
									},
								});
							}
						},
					});
				} else {
					uni.showToast({
						title: '最多上传三张图片',
						icon: 'loading',
						duration: 3000
					});
				}
			},
			/**
			 * 点击图片触发事件
			 * @method viewImgs
			 * @param e
			 */
			viewImgs(e) {
				const viewId = e.currentTarget.dataset.index;
				const viewImgs = [];
				const _this = this;
				for (let i = 0; i < _this.images.length; i++) {
					viewImgs.push(_this.images[i])
				}
				uni.previewImage({
					current: viewId,
					urls: viewImgs,
				});
			},
			/**
			 * 点击删除图片触发事件
			 * @method removeImg
			 * @param e
			 */
			removeImg(e) {
				const removeId = e.currentTarget.dataset.index;
				uni.showModal({
					content: '您确定要删除当前图片吗？',
					success: (e) => {
						if (e.confirm) {
							const newFilename = this.files[removeId];
							const filename = newFilename.substring(newFilename.lastIndexOf("/") + 1);
							this.images.splice(removeId, 1);
							this.files.splice(removeId, 1);
							this.images = this.images;
							this.files = this.files;
							// 调用删除图片接口
							let userInfoData = uni.getStorageSync('userInfo');
							let header = {
								'content-type': 'application/x-www-form-urlencoded',
								'Authorization': userInfoData.token
							};
							const prams = '{"filename":"' + filename + '","userId":"' + this.userId +
							'"}';
							this._imageDelete(prams, header);
						}
					}
				});
			},
			/**
			 * 点击提交按钮触发事件
			 * @method viewImgs
			 * @param e
			 */
			save(e) {
				this.isDisabled = true;
				uni.showLoading();
				if (this.content == "") {
					uni.hideLoading();
					uni.showToast({
						title: '请输入遇到的问题或建议',
						success: () => {
							this.isDisabled = false;
							uni.hideLoading();
						}
					})
				} else if (!this.verifyTel(this.phone)) {
					uni.hideLoading();
					uni.showToast({
						title: '请输入正确的手机号',
						success: () => {
							this.isDisabled = false;
							uni.hideLoading();
						}
					});
				} else {
					// 提交
					if (this.files[0]) {
						const files = this.files;
						let imagePaths = '';
						for (let i = 0; i < files.length; i++) {
							imagePaths += files[i]
						}
						imagePaths = files;
						let userInfoData = uni.getStorageSync( 'userInfo');
						let header = {
							'content-type': 'application/x-www-form-urlencoded',
							'Authorization': userInfoData.token
						};
						// const prams = ''+imagePaths+'data:{"userId":"'+this.data.userId+'","content":"'+this.data.content+'","mobile":"'+this.data.phone+'"}';
						const data = '{"userId":"' + this.userId + '","content":"' + this.content +
							'","mobile":"' + this.phone + '"}'
						this._addFeedback(imagePaths, data, header);
					} else {
						let userInfoData = uni.getStorageSync('userInfo');
						let header = {
							'content-type': 'application/x-www-form-urlencoded',
							'Authorization': userInfoData.token
						};
						// const files = this.data.files;
						// let imagePaths = '';
						// for(let i = 0; i < files.length; i++) {
						//   imagePaths += files[i]
						// }
						// imagePaths = files;
						// const prams = ''+imagePaths+'data:{"userId":"'+this.data.userId+'","content":"'+this.data.content+'","mobile":"'+this.data.phone+'"}';
						const data = '{"userId":"' + this.userId + '","content":"' + this.content +
							'","mobile":"' + this.phone + '"}'
						this._addFeedback('', data, header);
					}

				}
			},
			/**
			 * 检验手机号是否正确
			 * @method verifyTel
			 * @param {*} number // 手机号
			 */
			verifyTel(number) { // 手机号正则校验
				const reg = /^1[3|4|5|6|7|8|9]\d{9}$/;
				return reg.test(number);
			},
			//-------------------网络请求---------------------
			_imageDelete(prams, header) {
				imageDelete(prams, header).then(res => {
					const data = res.data;
					if (data.resultCode != "0000") {
						uni.showToast({
							title: res.data.resultMsg,
							success: () => {
								uni.hideLoading();
							}
						});
					} else {
						// const carList = data.data.carInfoList;
						// this.setData({carList});
						// my.hideLoading();
					}
				}).catch(err => {
					console.log(err);
					uni.hideLoading();
				})
			},
			_addFeedback(imagePaths, data, header) {
				addFeedback(imagePaths, data, header).then(res => {
					const data = res.data;
					if (data.resultCode != "0000") {
						uni.hideLoading();
						uni.showToast({
							title: res.data.resultMsg,
							success: () => {
								this.isDisabled = false;
								uni.hideLoading();
							}
						});
					} else {
						uni.hideLoading();
						uni.showToast({
							title: '提交成功',
							success: () => {
								this.isDisabled = false;
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/profile/profile'
									})
								}, 1500)
								
							}
						});
					}
				}).catch(err => {
					console.log(err);
					this.isDisabled = false;
					uni.hideLoading();
				})
			}
		},
		onLoad() {
			const _this = this;
			_this.files = [];
			uni.getStorage({
				key: 'userInfo',
				success: function(res) {
					_this.userId = res.data.userId;
					_this.mobile = res.data.mobile
				}
			})
		},
		onShow() {
			this.isDisabled = false;
		}
	}
</script>

<style>
	@import url("./feedback.css");
</style>
